import { createStore } from "vuex";
import { login, getInfo,logout } from "~/api/manger";
import { getToken, setToken,removeToken } from "~/composables/auth";
const store = createStore({
  state() {
    return {
      user: {}, // 用户信息
      menus:[],
      ruleNames:[],
      asideWidth:'250px',//侧边宽度
    };
  },
  mutations: {
    //记录用户信息
    SET_UEERINFO(state, user) {
      state.user = user;
    },
    // 展开收起菜单
    handleAsideWidth(state){
      console.log(state)
      state.asideWidth=state.asideWidth=="250px"?"64px":'250px'
    },
    SET_MENUS(state,menus){
      state.menus=menus
    },
    SET_RULENAMES(state,ruleNames){
      state.ruleNames=ruleNames
    }
  },
  actions: {
    login({ commit }, { userName, password }) {
      return new Promise((resolve, reject) => {
        login(userName, password)
          .then((res) => {
            setToken(res.token);
            resolve(res.token);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 获取当前用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const {menus,ruleNames}=res
            commit("SET_UEERINFO", res);
            commit("SET_MENUS", menus);
            commit("SET_RULENAMES", ruleNames);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout({commit}){
      commit('SET_UEERINFO',{})
      removeToken()
    }
  },
});

export default store;
